package com.bwie.unit;

import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.Ordered;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

@Configuration
public class GateWayUnit implements GlobalFilter, Ordered {

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {

        ServerHttpRequest request = exchange.getRequest();
        ServerHttpResponse response = exchange.getResponse();
        String s = request.getPath().toString();
        if(s.contains("/user/login")){
            System.out.println("允许放行");
            return chain.filter(exchange);
        }


//        String token = request.getHeaders().getFirst("token");
//        Claims body = Jwts.parser().setSigningKey("bw".getBytes()).parseClaimsJws(token).getBody();
//        Integer uid = body.get("uid", Integer.class);
//        String key = "token:"+uid;
//        String s1 = stringRedisTemplate.opsForValue().get(key);
//
//        String s2 = request.getRemoteAddress().getAddress().toString();
//        if (!s2.contains("127.0.0.1")){
//            System.out.println("异地登录");
//            response.setStatusCode(HttpStatus.UNAUTHORIZED);
//            return response.setComplete();
//        }


        return chain.filter(exchange);
    }

    @Override
    public int getOrder() {
        return 0;
    }
}
